// pages/login/login.js
import store from "../../store/index";
import create from "../../utils1/create";

create.Page(store, {
  use: ['isToken', "infouser", "globhttp"],
  data: {
    openid: "",
    session_key: "",
    UserCode: "",
    UserPass: "",
    UserWxOpenID: "",
    show: false,
    title: '请阅读并同意使用协议及隐私政策',
    checked: false,
    tipsCode: "获取验证码",
    infouser: [],
    timeNum: 60,
    clikType: false,
    phone: '',
    phoneCode: "",
    cardnumber: '',
    isHidden: true,
    timer: null
  },

  subscribeMessage() {
    wx.requestSubscribeMessage({
      tmplIds: ['3FduAIiDzqqYYlFd-jnYYdDtMxsl0cv95AwU3guK-Wk'],
      success(res) {
        if (res['3FduAIiDzqqYYlFd-jnYYdDtMxsl0cv95AwU3guK-Wk'] === 'accept') {
          wx.showToast({
            title: '订阅成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '订阅失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('订阅消息失败', err);
      }
    });
  },

  getPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const codes = e.detail.code;
      this.decryptPhoneNumber(codes)
    } else {
      console.log('获取手机号失败', e.detail);
    }
  },
  decryptPhoneNumber(codes) {
    wx.request({
      url: store.data.globhttp + "OneKeyChkLogin",
      method: 'POST',
      header: {
        'content-type': 'application/json',
        "content-type": "application/x-www-form-urlencoded"
      },
      data: JSON.stringify({
        UserWxCode:codes,
        UserWxOpenId:this.data.openid
      }),
      success: (res) => {
        if (res.data.RltCode === 1) {
          wx.showToast({
            icon: 'loading',
            title: '登录中',
            mask: true
          });
          setTimeout(() => {
            wx.hideLoading();
          }, 1000);
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            });
            const {
              Token_Code,
              ...infouser
            } = JSON.parse(res.data.RltData);
            wx.setStorageSync('token', Token_Code);
            wx.setStorageSync('infouser', infouser);
            store.data.infouser = infouser;
            store.data.isToken = Token_Code;
            wx.setStorageSync('openid', this.data.openid);
            store.data.openid = this.data.openid;
            if (infouser.Pson_Tel==null||infouser.Pson_Tel=="") {
              wx.showModal({
                title: '温馨提示',
                content: '您尚未绑定手机号，请绑定后继续使用',
                success: (res) => {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/xgphone/xgphone?id=0'
                    });
                  }
                }
              });
            }
          }, 2000);
        } else {
          wx.showToast({
            icon: "none",
            title: `手机号获取失败,请尝试手动输入操作`,
            duration: 2000
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          icon: "none",
          title: `手机号获取失败,请尝试手动输入操作`,
          duration: 2000
        });
        console.error('请求失败:', err);
      }
    });
  },

  goToAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/agreement',
    });
  },

  login() {
    if (!this.data.checked) {
      wx.showToast({
        icon: "none",
        title: '请阅读并同意使用协议及隐私政策',
        duration: 2000
      });
      return;
    }
    if (!this.data.UserCode) {
      wx.showToast({
        icon: "none",
        title: '请输入您的手机号或身份证号',
        duration: 2000
      });
      return;
    }
    if (!this.data.UserPass) {
      wx.showToast({
        icon: "none",
        title: '请输入密码',
        duration: 2000
      });
      return;
    }

    wx.login({
      success: (res) => {
        wx.request({
          url: store.data.globhttp + "CheckPsonUser",
          method: 'POST',
          header: {
            'content-type': 'application/json',
            "content-type": "application/x-www-form-urlencoded"
          },
          data: JSON.stringify({
            UserCode: this.data.UserCode,
            UserPass: this.data.UserPass,
            UserWxOpenId: this.data.openid
          }),
          success: (res) => {
            if (res.data.RltCode === 1) {
              wx.showToast({
                icon: 'loading',
                title: '登录中',
                mask: true
              });
              setTimeout(() => {
                wx.hideLoading();
              }, 1000);
              setTimeout(() => {
                const {
                  Token_Code,
                  ...infouser
                } = JSON.parse(res.data.RltData);
                wx.setStorageSync('token', Token_Code);
                wx.setStorageSync('infouser', infouser);
                store.data.infouser = infouser;
                store.data.isToken = Token_Code;
                  const openid = this.data.openid;
                  wx.setStorageSync('openid', openid);
                store.data.openid = openid;
                wx.switchTab({
                  url: '/pages/index/index'
                });

                if (infouser.Pson_Tel==null||infouser.Pson_Tel=="") {
                  wx.showModal({
                    title: '温馨提示',
                    content: '您尚未绑定手机号，请绑定后继续使用',
                    success: (res) => {
                      if (res.confirm) {
                        wx.navigateTo({
                          url: '/pages/xgphone/xgphone?id=0'
                        });
                      }
                    }
                  });
                }
              }, 2000);
            } else {
              wx.showToast({
                icon: "none",
                title: `${res.data.RltMsg}`,
                duration: 2000
              });
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
        });
      }
    });
  },

  doindex() {
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },

  doRegister() {
    wx.navigateTo({
      url: '/pages/Register/Register'
    });
  },

  handleChecked(e) {
    this.setData({
      checked: !this.data.checked
    });
  },

  inputChange(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  bindKeyInput(e) {
    const {
      inputname
    } = e.currentTarget.dataset;
    this.setData({
      [inputname]: e.detail.value
    });
  },

  onLoad(options) {
    setTimeout(() => {
      this.setData({
        isHidden: false
      });
    }, 500);

    const openids = wx.getStorageSync('openid');
    if (!openids) {
      wx.login({
        success: (res) => {
          wx.request({
            url: store.data.globhttp + "GetPsonWxOpenId",
            method: 'POST',
            header: {
              'content-type': 'application/json',
              "content-type": "application/x-www-form-urlencoded"
            },
            data: JSON.stringify({
              UserWxCode: res.code
            }),
            success: (res) => {
              console.log("res",res)
              const {
                openid
              } = JSON.parse(res.data.RltData);
              this.setData({
                openid:openid
              });
              // wx.setStorageSync('openid', openid);
            }
          });
        }
      });
    }else{
       this.data.openid=openids
       this.setData({
        openid:this.data.openid
      });
    }
  },

  onReady() {
    console.log("first", store.data.infouser);
  },

  onShow() {},

  onHide() {},

  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  onPullDownRefresh() {},

  onReachBottom() {},

  onShareAppMessage() {}
});